package com.hzdracom.epubreader.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ExpandableListView;

import com.google.inject.Inject;
import com.hzdracom.epubreader.fragment.ContentBookmarkFragment;
import com.shwread.android.qysw10000152.R;

import net.nightwhistler.pageturner.Configuration;
import net.nightwhistler.pageturner.activity.NavigationAdapter;
import net.nightwhistler.pageturner.activity.ReadingFragment;
import net.nightwhistler.pageturner.view.NavigationCallback;

import java.util.ArrayList;
import java.util.List;

import roboguice.RoboGuice;
import roboguice.activity.RoboFragmentActivity;
import roboguice.inject.InjectFragment;
import roboguice.inject.InjectView;

public class ReadingEpubActivity extends RoboFragmentActivity implements
		ExpandableListView.OnGroupClickListener,
		ExpandableListView.OnChildClickListener,
		AdapterView.OnItemLongClickListener {

	public static ReadingEpubActivity instance;

	@InjectFragment(R.id.fragment_reading)
	private ReadingFragment readingFragment;
	@InjectView(R.id.drawer_layout)
	private DrawerLayout mDrawer;

	// @InjectView(R.id.left_drawer)
	// private ExpandableListView mDrawerOptions;

	@InjectFragment(R.id.fragment_contents)
	private ContentBookmarkFragment contentsFragment;

	@Inject
	private Configuration config;

	private NavigationAdapter adapter;

	private int tocIndex = -1;
	private int highlightIndex = -1;
	private int searchIndex = -1;
	private int bookmarksIndex = -1;
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Configuration config = RoboGuice.getInjector(this).getInstance(
				Configuration.class);
		changeLanguageSetting(this, config);
		// 设置无标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 设置全屏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.epub3_activity_reading);
		instance = this;

		// set a custom shadow that overlays the main content when the drawer
		mDrawer.setDrawerShadow(R.drawable.epub3_drawer_shadow, GravityCompat.START);
		mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

		initDrawerItems();

		DrawerLayout.DrawerListener toggle = new DrawerLayout.DrawerListener() {

			@Override
			public void onDrawerClosed(View arg0) {
			}

			@Override
			public void onDrawerOpened(View arg0) {
				initDrawerItems();
			}

			@Override
			public void onDrawerSlide(View arg0, float arg1) {

			}

			@Override
			public void onDrawerStateChanged(int arg0) {

			}
		};
		mDrawer.setDrawerListener(toggle);
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		return super.onPrepareOptionsMenu(menu);
	}

	public void initDrawerItems() {
		contentsFragment.initContentsBookmarks(readingFragment,
				ReadingEpubActivity.this);
	}

	protected void initDrawerItems(ExpandableListView expandableListView) {
		if (expandableListView != null) {

			this.adapter = new NavigationAdapter(this, getMenuItems(config));

			expandableListView.setAdapter(this.adapter);
			expandableListView.setOnGroupClickListener(this);
			expandableListView.setOnChildClickListener(this);

			expandableListView.setGroupIndicator(null);
		}

		if (expandableListView == null) {
			return;
		}

		expandableListView.setOnItemLongClickListener(this);

		if (this.readingFragment != null) {

			List<NavigationCallback> tocCallbacks = this.readingFragment
					.getTableOfContents();

			if (tocCallbacks != null && !tocCallbacks.isEmpty()) {
				getAdapter().setChildren(this.tocIndex, tocCallbacks);
			}

			List<NavigationCallback> highlightCallbacks = this.readingFragment
					.getHighlights();

			if (highlightCallbacks != null && !highlightCallbacks.isEmpty()) {
				getAdapter().setChildren(this.highlightIndex,
						highlightCallbacks);
			}

			List<NavigationCallback> searchCallbacks = this.readingFragment
					.getSearchResults();

			if (searchCallbacks != null && !searchCallbacks.isEmpty()) {
				getAdapter().setChildren(this.searchIndex, searchCallbacks);
			}

			List<NavigationCallback> bookmarkCallbacks = this.readingFragment
					.getBookmarks();

			if (bookmarkCallbacks != null && !bookmarkCallbacks.isEmpty()) {
				getAdapter()
						.setChildren(this.bookmarksIndex, bookmarkCallbacks);
			}

		}
	}

	private NavigationAdapter getAdapter() {
		return adapter;
	}

	protected String[] getMenuItems(Configuration config) {

		List<String> menuItems = new ArrayList<String>();

		menuItems.add("Setting");
		menuItems.add("Open Epub");

		menuItems.add(config.getLastReadTitle());

		if (this.readingFragment != null) {

			if (this.readingFragment.hasTableOfContents()) {
				menuItems.add(getString(R.string.toc_label));
				this.tocIndex = menuItems.size() - 1;
			}

			if (this.readingFragment.hasHighlights()) {
				menuItems.add(getString(R.string.highlights));
				this.highlightIndex = menuItems.size() - 1;
			}

			if (this.readingFragment.hasSearchResults()) {
				menuItems.add(getString(R.string.search_results));
				this.searchIndex = menuItems.size() - 1;
			}

			if (this.readingFragment.hasBookmarks()) {
				menuItems.add(getString(R.string.bookmarks));
				this.bookmarksIndex = menuItems.size() - 1;
			}

		}

		return menuItems.toArray(new String[menuItems.size()]);
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		setProgressBarIndeterminate(true);
		setProgressBarIndeterminateVisibility(false);
	}

	public static void changeLanguageSetting(Context context,
			Configuration pageTurnerConfig) {
		android.content.res.Configuration config = new android.content.res.Configuration(
				context.getResources().getConfiguration());

		config.locale = pageTurnerConfig.getLocale();
		context.getResources().updateConfiguration(config,
				context.getResources().getDisplayMetrics());
	}

	@Override
	public boolean onSearchRequested() {
		readingFragment.onSearchRequested();
		return true;
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		readingFragment.onWindowFocusChanged(hasFocus);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return readingFragment.onTouchEvent(event);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		int action = event.getAction();
		int keyCode = event.getKeyCode();

		if (action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK
				&& isDrawerOpen()) {
			closeNavigationDrawer();
			return true;
		}

		if (readingFragment.dispatchKeyEvent(event)) {
			return true;
		}

		return super.dispatchKeyEvent(event);
	}

	private boolean isDrawerOpen() {
		return mDrawer.isDrawerOpen(GravityCompat.START);
	}

	public void closeNavigationDrawer() {
		mDrawer.closeDrawers();
	}

	public void openNavigationDrawer() {
		mDrawer.openDrawer(GravityCompat.START);
	}

	public void setDrawerUseable(boolean use) {
		if (use) {
			mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
		} else {
			mDrawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
		}
	}

	@Override
	public boolean onGroupClick(ExpandableListView expandableListView,
			View view, int i, long l) {
		int correctedIndex = getCorrectIndex(i);

		// FIXME: this is nasty and hacky!
		if (correctedIndex == 2 || i == tocIndex || i == highlightIndex
				|| i == searchIndex || i == bookmarksIndex) {
			return false;
		}

		if (i == 0) {
			this.readingFragment.openSetting();
		} else if (i == 1) {
			this.readingFragment.launchFileManager();
		}

		closeNavigationDrawer();
		return true;
	}

	private int getCorrectIndex(int i) {
		return i;
	}

	@Override
	public boolean onChildClick(ExpandableListView expandableListView,
			View view, int i, int i2, long l) {
		closeNavigationDrawer();
		NavigationCallback childItem = adapter.getChild(i, i2);

		if (childItem != null) {
			childItem.onClick();
		}

		return false;
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {

		if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
			int groupPosition = ExpandableListView.getPackedPositionGroup(id);
			int childPosition = getAdapter().getIndexForChildId(groupPosition,
					ExpandableListView.getPackedPositionChild(id));

			NavigationCallback childItem = getAdapter().getChild(groupPosition,
					childPosition);

			if (childItem != null) {
				childItem.onLongClick();
			}

			closeNavigationDrawer();
			return true;
		}

		return false;
	}
}
